package com.pansoft.openplanet.fragment;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.efounder.chat.activity.ChatRoomActivity;
import com.efounder.chat.activity.GroupNotifacationActivity;
import com.efounder.chat.activity.NewFriendsActivity;
import com.efounder.chat.activity.TransformFragmentActivity;
import com.efounder.chat.fragment.PublicNumberListFragment;
import com.efounder.chat.fragment.TreeFragment;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.mobilecomps.contacts.ClearEditText;
import com.efounder.mobilecomps.contacts.HanyuParser;
import com.efounder.mobilecomps.contacts.SideBar;
import com.efounder.tbs.Md5Tool;
import com.efounder.thirdpartycomps.stickylistheaders.StickyListHeadersListView;
import com.efounder.util.ToastUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.MobileContactDetailActivity;
import com.pansoft.openplanet.adapter.MobileContactsAdapter;
import com.pansoft.openplanet.bean.Contact;
import com.pansoft.openplanet.util.MobileContactsPinyinComparator;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.TCLoadingDataView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;

/**
 * Created by will on 18-3-21.
 */

public class MobileContactsFragment extends BaseFragment implements
        AdapterView.OnItemClickListener,
        StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener {
    private StickyListHeadersListView stickyList;
    private SideBar sideBar;
    private TextView dialog;
    private MobileContactsAdapter adapter;
    private ClearEditText mClearEditText;
    private boolean fadeHeader = true;
    private final static String TAG = "MobileContactsFragment";
    /**
     * 汉字转换成拼音的类
     */
    private List<Contact> sourceDataList = new ArrayList<>();
    private List<Contact> rawDataList = new ArrayList<>();

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private MobileContactsPinyinComparator pinyinComparator;

    LayoutInflater inflater = null;
    private TextView tv_loadview;
    private boolean hasLoad = false;//是否已经加载数据


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(com.efounder.chat.R.layout.fragment_contacts, container,
                false);
        this.inflater = inflater;
        initViews(view);
        //getContactFromLocal();
        return view;
    }

    private void getContactFromLocal() {
        //stickyList.setVisibility(View.GONE);
        // tv_loadview.setVisibility(View.VISIBLE);
      Disposable disposable=  Observable.create(new ObservableOnSubscribe<List<Contact>>() {
            @Override
            public void subscribe(ObservableEmitter<List<Contact>> emitter) throws Exception {
                rawDataList.clear();
                rawDataList = getContacts();
                rawDataList = filledData(rawDataList);
                Collections.sort(rawDataList, pinyinComparator);
                emitter.onNext(rawDataList);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
//                .observeOn(Schedulers.io()).map(new Function<List<Contact>, List<Contact>>() {
//            @Override
//            public List<Contact> apply(List<Contact> contacts) throws Exception {
//                contacts = filledData(contacts);
//                Collections.sort(contacts, pinyinComparator);
//                return contacts;
//            }
//        })
                .observeOn(AndroidSchedulers.mainThread()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                TCLoadingDataView.show(getActivity(), R.string.common_text_loading);
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<Contact>>() {
                    @Override
                    public void accept(List<Contact> contacts) throws Exception {
                        TCLoadingDataView.dismiss();
                        stickyList.setVisibility(View.VISIBLE);
                        tv_loadview.setVisibility(View.GONE);
                        // reloadData();
                        sourceDataList.clear();
                        sourceDataList.addAll(contacts);
                        adapter.notifyDataSetChanged();
                        getContactFromServer();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        TCLoadingDataView.dismiss();
                        //stickyList.setVisibility(View.VISIBLE);
                        // tv_loadview.setVisibility(View.GONE);
                        ToastUtil.showToast(getActivity().getApplicationContext(), "获取联系人失败");
                    }
                });
    }

    public Observable getContacatObservable() {
        return Observable.create(new ObservableOnSubscribe<List<Contact>>() {
            @Override
            public void subscribe(ObservableEmitter<List<Contact>> emitter) throws Exception {
                rawDataList.clear();
                rawDataList = getContacts();
                emitter.onNext(rawDataList);
                emitter.onComplete();
            }
        });
    }

    public Observable getServerContacatObservable() {
        return Observable.create(new ObservableOnSubscribe<Response>() {
            @Override
            public void subscribe(ObservableEmitter<Response> emitter) throws Exception {
//                HashMap<String, String> paramsMap = new HashMap<>();
//                paramsMap.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
//                String url = TCRequestUtil.BASE_URL + "/linkMan/getLinkMans";
//                Response response = CommonRequestManager.getInstance(getActivity()).requestGetBySyn(TAG, url, paramsMap);
//                emitter.onNext(response);
//                emitter.onComplete();
            }
        });
    }

    private void initViews(View view) {
        // 实例化汉字转拼音类

        pinyinComparator = new MobileContactsPinyinComparator();
        tv_loadview = view.findViewById(com.efounder.chat.R.id.tv_loadview);
        sideBar = view.findViewById(com.efounder.chat.R.id.sidrbar);
        dialog = view.findViewById(com.efounder.chat.R.id.dialog);
        sideBar.setTextView(dialog);

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    stickyList.setSelection(position);
                }

            }
        });

        stickyList = view
                .findViewById(com.efounder.chat.R.id.country_lvcountry);
        stickyList.setOnItemClickListener(this);
        stickyList.setOnHeaderClickListener(this);
        stickyList.setOnStickyHeaderChangedListener(this);
        stickyList.setOnStickyHeaderOffsetChangedListener(this);
        // stickyList.addHeaderView(getLayoutInflater().inflate(R.layout.list_header,
        // null));
        // stickyList.addFooterView(getLayoutInflater().inflate(R.layout.list_footer,
        // null));
        // stickyList.setEmptyView(findViewById(R.id.empty));
        stickyList.setDrawingListUnderStickyHeader(true);
        stickyList.setAreHeadersSticky(true);
        stickyList.setStickyHeaderTopOffset(-10);
        stickyList.setFastScrollEnabled(true);
        stickyList.setFastScrollAlwaysVisible(true);
        //stickyList.addHeaderView(topLayout);


        adapter = new MobileContactsAdapter(getActivity(), sourceDataList);
        stickyList.setAdapter(adapter);

        mClearEditText = view.findViewById(com.efounder.chat.R.id.filter_edit);

        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i(TAG, "onHiddenChanged:" + hidden);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.i(TAG, "setUserVisibleHint:" + isVisibleToUser);
        if (!hasLoad && isVisibleToUser) {
            hasLoad = true;
            getContactFromLocal();
        }
    }

    private void reloadData() {
        sourceDataList.clear();
        List<Contact> myList = new ArrayList<>();
        myList.addAll(rawDataList);
        sourceDataList.addAll(filledData(myList));
        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        adapter.notifyDataSetChanged();

    }


    /**
     * 为ListView填充数据
     *
     * @param users
     * @return
     */
    private List<Contact> filledData(List<Contact> users) {
        List<Contact> usersList = new ArrayList<>();

        for (Contact user : users) {
            // 汉字转换成拼音
            String userName = user.getName();
            if (userName == null) {
                userName = "未知";
            }
            String pinyin = new HanyuParser().getStringPinYin(userName);
            String sortString = pinyin.substring(0, 1).toUpperCase(
                    Locale.getDefault());
            if (userName != null) {
                if (userName.equals("群聊") || userName.equals("新的朋友") || userName.equals("群通知")) {
                    user.setSortLetters("↑");
                } else if (userName.equals("")) {
                    user.setSortLetters("☆");
                } else if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
                    user.setSortLetters(sortString.toUpperCase(Locale.getDefault()));
                } else {
                    user.setSortLetters("#");
                }
                usersList.add(user);
            } else {

            }
        }
        return usersList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<Contact> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDataList;
        } else {
            filterDateList.clear();
            for (Contact user : sourceDataList) {
                String name = user.getName();
                if (containString(name, filterStr)) {
                    filterDateList.add(user);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    private boolean containString(String name, String filterStr) {
        if (name == null) {
            name = "未知用户";
        }
        String namePinyin = new HanyuParser().getStringPinYin(name);
        for (int i = 0; i < filterStr.length(); i++) {
            String singleStr = filterStr.substring(i, i + 1);
            // 汉字
            if (name.contains(singleStr)) {
                if (i == filterStr.length() - 1) {
                    return true;
                }
                continue;
            }
            // 英文
            if (namePinyin.contains(singleStr)) {
                int currentIndex = namePinyin.indexOf(singleStr);
                namePinyin = namePinyin.substring(currentIndex + 1,
                        namePinyin.length());
            } else {// 不包含
                break;
            }
            if (i == filterStr.length() - 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onStickyHeaderOffsetChanged(StickyListHeadersListView l,
                                            View header, int offset) {
        if (fadeHeader
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
        }
    }

    @Override
    public void onStickyHeaderChanged(StickyListHeadersListView l, View header,
                                      int itemPosition, long headerId) {
        header.setAlpha(1);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {

        Contact user = (Contact) adapter.getItem(position);
        if ("↑".equals(user.getSortLetters())) {
            String remark = user.getName();
            if ("公众号".equals(remark)) {

                Intent intent = new Intent(getActivity(),
                        TransformFragmentActivity.class);
                intent.putExtra(TransformFragmentActivity.EXTRA_FRAGMENT_NAME,
                        PublicNumberListFragment.class.getName());
                startActivity(intent);

            } else if ("群聊".equals(remark)) {
                Intent intent = new Intent(getActivity(),
                        ChatRoomActivity.class);
                startActivity(intent);

            } else if ("组织机构".equals(remark)) {
                Intent intent = new Intent(getActivity(),
                        TransformFragmentActivity.class);
                intent.putExtra(TransformFragmentActivity.EXTRA_FRAGMENT_NAME,
                        TreeFragment.class.getName());
                startActivity(intent);
            } else if ("新的朋友".equals(remark)) {
                Intent intent = new Intent(getActivity(),
                        NewFriendsActivity.class);
                startActivity(intent);
            } else if ("群通知".equals(remark)) {
                Intent intent = new Intent(getActivity(),
                        GroupNotifacationActivity.class);
                startActivity(intent);
            }
        } else {
            Intent intent = new Intent(getActivity(), MobileContactDetailActivity.class);
            intent.putExtra("contact", user);
            startActivityForResult(intent, 5);
        }
    }

    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header,
                              int itemPosition, long headerId, boolean currentlySticky) {
        // Toast.makeText(getActivity(),
        // "Header " + headerId + " currentlySticky ? " + currentlySticky,
        // Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        RefWatcher refWatcher = TalcChainApplication.getRefWatcher(getActivity());
//        refWatcher.watch(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "");
    }

    public List<Contact> getContacts() {
        List<Contact> contacts = new ArrayList<>();
        try {

            Uri uri = Uri.parse("content://com.android.contacts/contacts");
            ContentResolver resolver = getActivity().getContentResolver();
            Cursor cursor = resolver.query(uri, new String[]{"_id"}, null, null, null);
            contacts.clear();
            while (cursor.moveToNext()) {
                int contactsId = cursor.getInt(0);
                Contact contact = new Contact();
                List<Contact.Phone> phones = new ArrayList<>();
                StringBuilder builder = new StringBuilder("contactsId=");
                builder.append(contactsId);
                uri = Uri.parse("content://com.android.contacts/contacts/" + contactsId + "/data");
                Cursor dataCursor = resolver.query(uri, new String[]{"mimetype", "data1", "data2", "data15"}, null, null, null);
                while (dataCursor.moveToNext()) {

                    String data = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                    if (data != null) {
                        data = data.replace(" ", "");
                    }
                    String phoneType = dataCursor.getString(dataCursor.getColumnIndex("data2"));
                    byte[] bytes = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
                    if (bytes != null) {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    }
                    String type = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
                    if ("vnd.android.cursor.item/name".equals(type)) {
                        if (data == null || data.equals("")) {
                            contact.setName("未知用户");
                        } else {
                            contact.setName(data);
                        }
                        contact.setId(String.valueOf(contactsId));
                        builder.append(", name=" + data);
                    } else if ("vnd.android.cursor.item/phone_v2".equals(type)) {
                        Contact.Phone phone = contact.new Phone();
                        phone.setPhone(data);
                        phone.setPhoneMd5(Md5Tool.hashKey(data));
                        // TODO: 18-3-21
                        if (phoneType != null) {
                            if ("1".equals(phoneType)) {
                                phone.setType("住宅");
                            } else if ("2".equals(phoneType)) {
                                phone.setType("手机");
                            } else if ("3".equals(phoneType)) {
                                phone.setType("单位");
                            }
                        } else {
                            phone.setType("其他");
                        }
                        builder.append(", phone=" + data);
                        builder.append(",phoneType=" + phoneType);
                        phones.add(phone);
                    }
                    contact.setPhones(phones);

                }
                dataCursor.close();
                Log.d("IMPORTCONTACTS", builder.toString());
                contacts.add(contact);
            }
            cursor.close();
            return contacts;
        } catch (Exception e) {
            e.printStackTrace();
            return contacts;
        }

    }

    public void getContactFromServer() {

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        String url = TCRequestUtil.BASE_URL + "/linkMan/getLinkMans";
        TCRequestUtil.getOAuthRequest(TAG, "linkMan/getLinkMans", paramsMap, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                final Map<String, String> map = new HashMap<>();
                try {
                    final JSONObject jsonObject = JSONObject.fromObject(response);
                    if (jsonObject.optString("result", "").equals("success")) {
                        CommonThreadPoolUtils.execute(new Runnable() {
                            @Override
                            public void run() {
                                JSONArray array = jsonObject.getJSONArray("linkMans");
                                for (int i = 0; i < array.size(); i++) {
                                    if (array.getJSONObject(i).containsKey("linkManId")) {
                                        map.put(array.getJSONObject(i).getString("linkManIdMd5"), "true");
                                    }
                                }

                                for (String key : map.keySet()) {
                                    for (Contact contact : sourceDataList) {
                                        if (contact.getPhones() != null) {
                                            for (Contact.Phone phone : contact.getPhones()) {
                                                if (key.equals(phone.getPhoneMd5().toUpperCase())) {
                                                    contact.setRegister(true);
                                                }
                                            }
                                        }
                                    }
                                }
                                if (getActivity() == null || getContext() == null) {
                                    return;
                                }
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        adapter.notifyDataSetChanged();
                                    }
                                });
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });

    }
}
